package cn.edu.glut.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.assertj.core.util.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.edu.glut.entity.Secretary;
import cn.edu.glut.user.repository.SecretaryRepository;
import cn.edu.glut.user.service.SecretaryService;
/**
 * 
 * @author Caizhfy
 * @version v.0.1
 * @createTime 2017年12月13日下午8:44:43
 * @email Caizhfy@163.com
 * @description
 *
 */
@Service
public class SecretaryServiceImpl implements SecretaryService{
	@Autowired
	private SecretaryRepository secretaryRepository;
	
	@Override
	public int save(Secretary s) {
		secretaryRepository.save(s);
		if(!StringUtils.isEmpty(s.getId()))
			return 1;
		return 0;
	}

	@Override
	public void delete(String id) {
		secretaryRepository.delete(id);
	}

	@Override
	public int update(Secretary s) {
		Preconditions.checkNotNull(secretaryRepository.findOne(s.getId()),"该秘书不存在");
		secretaryRepository.save(s);
		return 1;
	}

	@Override
	public Secretary findById(String id) {
		return secretaryRepository.findOne(id);
	}

	@Override
	public Page<Secretary> list(Pageable pageable, final String majorId) {
		return secretaryRepository.findAll(new Specification<Secretary>() {
			
			@Override
			public Predicate toPredicate(Root<Secretary> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> predicates = new ArrayList<Predicate>();
				if (!StringUtils.isEmpty(majorId)) {
					predicates.add(criteriaBuilder.equal(root.get("majorId"), majorId));
				}
				return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}, pageable);
	}

	@Override
	public void deleteAll() {
		secretaryRepository.deleteAllInBatch();
	}

	@Override
	public Secretary findByUsername(String username) {
		Secretary s = secretaryRepository.findByUsername(username);
		s.setPassword(null);
		return s;
	}
}
